package util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * @author Administrator
 */
public class JSONFormatUtil {

    /**
     * 将对象转为json后格式化，用于生成postman请求参数
     * @param obj
     * @return
     */
    public static String formatJSON(Object obj) {
        if (obj == null) {
            return "{}";
        }
        if (obj instanceof String) {
            obj = JSONObject.parseObject(obj.toString());
        }
        String pretty = JSON.toJSONString(obj, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);
        return pretty;
    }

    /**
     * 清洗日志方法， 将一行日志解析为json集合
     * @param log 一行日志
     * @return
     */
    public static JSONArray parseJSONArrsy(String log) {
        JSONArray jsonArrsy = new JSONArray();
        if (StringUtils.isEmpty(log)) {
            return jsonArrsy;
        }

        int endIndex = 0;
        while (log.contains("{") && log.contains("}")) {
            int startIndex = log.indexOf("{");
            endIndex = log.indexOf("}",endIndex+1);
            try {
                JSONObject json = parseJSON(log.substring(startIndex, endIndex+1));
                if (json == null) {
                    continue;
                } else {
                    jsonArrsy.add(json);
                    log = log.substring(endIndex);
                }
            } catch(Exception ee) {
                return jsonArrsy;
            }

        }

        return jsonArrsy;
    }

    /**
     * 字符串转json，忽略异常
     * @return
     */
    private static JSONObject parseJSON(String s) {
        try {
            return JSONObject.parseObject(s);
        } catch(Exception e) {
            return null;
        }
    }

    public static void removeEmpty(JSONObject json) {
        if (json == null) {
            return ;
        }
        List<Object> nullKeyList = new ArrayList<>();

        for (Object key : json.keySet()) {
            if (json.get(key) == null || StringUtils.isEmpty(json.get(key))) {
                nullKeyList.add(key);
            }
        }
        if (!CollectionUtils.isEmpty(nullKeyList)) {
            for (Object key : nullKeyList) {
                json.remove(key);
            }
        }
    }

    public static void main(String[] args) throws IOException {
    }
}
